package com.ecoolex.cms.system.core.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.cms.system.entity.SunrisedutyfreeApplication;
import com.ecoolex.cms.system.pojo.TokenDTO;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.RandomUtil;
import com.ecoolex.framework.modularize.api.service.cache.CacheService;


@Service
public class TokenManager {

	@Autowired
	private CacheService redisService;
	
	@Autowired
	private SunrisedutyfreeApplicationManager sunrisedutyfreeApplicationManager;

	private static final int expirytime = 24 * 60
		* 60;

	private static final int effectiveTime = expirytime * 1000;

	public TokenDTO createToken(SunrisedutyfreeApplication application) {
		String token = RandomUtil.randomString(128);
		if (redisService.has(token)) {
			return createToken(application);
		}

		TokenDTO dto = new TokenDTO();
		dto.setToken(token);
		dto.setExpirytime(expirytime);
		redisService.put(token, application.getAppId(), effectiveTime);
		return dto;
	}

	public SunrisedutyfreeApplication getSunrisedutyfreeApplicationByToken(String token) {
		String appId = redisService.get(token);
		if (Check.notNull(appId)) {
			return sunrisedutyfreeApplicationManager.getByAppid(appId);
		}
		return null;
	}

}
